import { message, Modal } from 'antd';
import React, { Component } from 'react';
import { axconst } from '@/shared/axconst';
import { axhelper } from '@/shared/axhelper';

/**
 * @param namespace Model的命名空间
 * @param firstLoadData 是否首次加载数据（默认：true）
 */
class AxStandardList extends Component<any, any> {
  axurl = {
    read: '/read',
    create: '/create',
    update: '/update',
    destroy: '/destroy',
    total: '/total',
  };
  constructor(props: any, params: any) {
    super(props);
    const { needPage = true, namespace, firstLoadData = true, needTotal = false } = params;
    this.state = {
      /** Model的命名空间 */
      axNamespace: '',
      /** 新建表单是否可见 */
      axCreateVisible: false,
      /** 更新表单是否可见 */
      axUpdateVisible: false,
      /** 查询表单是否可见 */
      axSearchVisible: false,
      /** 选中的行数据 */
      axSelectedRows: [],
      /** 表单值 */
      axSearchFormValues: {},
      /** 配置表单的值 */
      axOperateValues: {},
      /** 配置操作按钮 */
      axButtons: [{}],
      /** 配置分页 */
      axPage: needPage === false ? {} : axconst.page.params,
      /** 配置排序 */
      axSort: {},
      /** 是否需要统计数据 */
      axNeedTotal: needTotal,
      /** Table展开的行 */
      axExpandedRowKeys: [],
    };
    if (namespace) {
      this.axNamespace = namespace;
      this.axurl = {
        read: `${this.axNamespace}/read`,
        create: `${this.axNamespace}/create`,
        update: `${this.axNamespace}/update`,
        destroy: `${this.axNamespace}/destroy`,
        total: `${this.axNamespace}/total`,
      };
    }
    this.axFirstLoadData = firstLoadData !== false;
    this.axTableRef = React.createRef();
    axhelper.getPermission();
  }

  /** 是否只选中一行数据 */
  axSelectedNotOnly = true;

  /** 是否没有选中数据 */
  axSelectedEmpty = true;

  /** 是否选择多行 */
  axSelectedNotOnlyOne = false;

  /** Model的命名空间 */
  axNamespace = '';

  /** 列表固定的querystring参数 */
  axParams = {};

  /** 是否首次加载数据（默认：true） */
  axFirstLoadData = false;

  /** 简单查询项 */
  searchOption: any = [];

  /** Table的ref */
  axTableRef: any = null;

  /** 会在组件挂载后（插入 DOM 树中）立即调用  --生命周期函数 */
  componentDidMount() {
    if (this.axFirstLoadData === true) {
      return this.axHandleRead();
    }
  }

  axHandleRead = (payload?: any) => {
    const { dispatch } = this.props;
    const { axPage, axSort, axNeedTotal } = this.state;

    if (axNeedTotal === true) {
      dispatch({
        type: this.axurl.total,
        params: this.axParams,
        payload: payload || {
          ...axSort,
          ...axPage,
        },
      });
    }
    /** 调用model中的fetch方法 */
    return dispatch({
      type: this.axurl.read,
      params: this.axParams,
      payload: payload || {
        ...axSort,
        ...axPage,
      },
    });
  };

  /** Table分页、排序、筛选事件的响应函数 */
  axHandleTableChange = (pagination: any, filtersArg: any, sorter: any) => {
    let { axPage, axSort, axSearchFormValues } = this.state;
    axPage = axconst.page.getParams(pagination);
    const payload = {
      ...axPage,
      ...axSearchFormValues,
    };

    if (sorter && sorter.field) {
      const sort = `${sorter.field} ${sorter.order === 'ascend' ? 'asc' : 'desc'}`;
      axSort.sort = sort;
    }

    this.setState({
      axPage,
      axSort,
    });
    this.axTableRef.current.cleanSelectedKeys();
    return this.axHandleRead({
      ...axSort,
      ...payload,
    });
  };

  /** 展开的行变化时触发 */
  axHandleExpandedRowsChange = (expandedRows: any) => {
    this.setState({
      axExpandedRowKeys: expandedRows,
    });
  };

  axHandleButtonsVisible = () => { };
  /** 选中行处理函数 */
  axHandleSelectRows = (rows: any) => {
    this.axSelectedNotOnly = rows.length !== 1;
    this.axSelectedEmpty = rows.length === 0;
    this.axSelectedNotOnlyOne = rows.length > 1;
    this.setState({
      axSelectedRows: rows,
    });
    if (this.axHandleButtonsVisible) {
      this.axHandleButtonsVisible();
    }
  };

  /** 查询处理函数 */
  axHandleSearch = (e: any, fieldsValue: any) => {
    /** 阻止默认事件 */
    if (e) e.preventDefault();
    const { axPage, axSort } = this.state;
    axPage.currentPage = 1;
    this.setState({
      axPage,
      axSearchFormValues: fieldsValue,
    });
    this.axTableRef.current.cleanSelectedKeys();
    return this.axHandleRead({
      ...axSort,
      ...axPage,
      ...fieldsValue,
    });
  };

  /** 重置查询
   * @param flag (clear：清空查询条件，read：清空并查询)
   */
  axHandleResetSearch = (flag = 'read') => {
    const { axPage, axSort } = this.state;
    if (flag === 'read') {
      axPage.currentPage = 1;
      this.setState({
        axPage,
        axSearchFormValues: {},
      });
      this.axTableRef.current.cleanSelectedKeys();
      return this.axHandleRead({
        ...axSort,
        ...axPage,
      });
    } else {
      this.setState({
        axSearchFormValues: {},
      });
    }
  };

  /** 刷新处理函数 */
  axHandleRefresh = () => {
    const { axSearchFormValues, axPage, axSort } = this.state;
    return this.axHandleRead({
      ...axSort,
      ...axPage,
      ...axSearchFormValues,
    });
  };

  /** 展示添加弹框 */
  axHandleCreateVisible = (flag?: boolean) => {
    this.setState({
      axCreateVisible: !!flag,
    });
  };

  /** 展示修改弹框 */
  axHandleUpdateVisible = (flag?: boolean) => {
    this.setState({
      axUpdateVisible: !!flag,
    });
  };

  /** 展示查询弹框 */
  axHandleSearchVisible = (flag?: boolean) => {
    this.setState({
      axSearchVisible: !!flag,
    });
  };

  /** 获取要修改的行信息，并展示修改弹框 */
  axHandleUpdateValues = (flag: boolean, record: any) => {
    const { axSelectedRows } = this.state;
    const operateValues =
      record ||
      (axSelectedRows && axSelectedRows.length > 0 ? axSelectedRows[0] : undefined) ||
      undefined;
    if (operateValues) {
      this.axHandleUpdateVisible(flag);
      this.setState({
        axOperateValues: operateValues,
      });
    }
  };

  /** 添加处理函数 */
  axHandleCreate = (fields: any) => {
    const { dispatch } = this.props;
    return dispatch({
      type: this.axurl.create,
      params: this.axParams,
      payload: {
        ...this.axParams,
        ...fields,
      },
      // callback: () => {
      //   message.success('添加成功');
      //   this.axHandleCreateVisible();
      //   this.fetchFirstPage();
      // },
    }).then(() => {
      message.success('添加成功');
      this.axHandleCreateVisible();
      this.fetchFirstPage();
    });
  };

  /** 保存并继续处理函数 */
  axHandleContinue = (fields: any) => {
    const { dispatch } = this.props;
    return dispatch({
      type: this.axurl.create,
      params: this.axParams,
      payload: {
        ...this.axParams,
        ...fields,
      },
      // callback: () => {
      //   message.success('添加成功');
      //   this.fetchFirstPage();
      // },
    }).then(() => {
      message.success('添加成功');
      this.fetchFirstPage();
    });
  };

  /** 修改处理函数 */
  axHandleUpdate = (fields: any) => {
    const { dispatch } = this.props;
    return dispatch({
      type: this.axurl.update,
      params: this.axParams,
      payload: {
        ...this.axParams,
        ...fields,
      },
      // callback: () => {
      //   message.success('修改成功');
      //   this.axHandleUpdateVisible();
      //   this.fetchFirstPage();
      // },
    }).then(() => {
      message.success('修改成功');
      this.axHandleUpdateVisible();
      this.fetchFirstPage();
    });
  };

  /** 删除多条数据处理函数 */
  axHandleDelete = (operate: any) => {
    const ids: any[] = [];
    this.state.axSelectedRows.forEach((i: any) => {
      ids.push(i.id);
    });
    const { dispatch } = this.props;
    dispatch({
      type: this.axurl.destroy,
      params: this.axParams,
      payload: { ids },
      // callback: () => {
      //   message.success(`${operate}成功`);
      //   this.fetchFirstPage();
      // },
    }).then(() => {
      message.success(`${operate}成功`);
      this.fetchFirstPage();
    });
  };

  /** 删除单条数据处理函数
   *  @param record 删除的记录
   *  @param idName id名称，如：shemeId（默认为id）
   */
  axHandleDeleteSingle = (record: any, idName: any) => {
    const id: any = {};
    if (idName) {
      id[idName] = record.id;
    } else {
      id.id = record.id;
    }
    const { dispatch } = this.props;
    dispatch({
      type: this.axurl.destroy,
      params: this.axParams,
      payload: id,
      // callback: () => {
      //   message.success('删除成功');
      //   this.fetchFirstPage();
      // },
    }).then(() => {
      message.success('删除成功');
      this.fetchFirstPage();
    });
  };

  /** 操作确认 */
  axConfirm = (operate: any, handle: any) => {
    const { axSelectedRows } = this.state;
    if (axSelectedRows.length > 0) {
      Modal.confirm({
        title: '操作确认',
        content: `确认对这${axSelectedRows.length}条数据进行${operate}操作？`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => handle(operate),
      });
    }
  };

  /** 引用AxTable组件 */
  onAxTableRef = (ref: any) => {
    this.axTableRef.current = ref;
  };

  /** 查询首页 */
  fetchFirstPage = () => {
    const { axPage, axSort, axSearchFormValues } = this.state;
    if (axPage.currentPage) {
      axPage.currentPage = 1;
    }
    return this.axHandleRead({
      ...axSort,
      ...axPage,
      ...axSearchFormValues,
    });
  };

  axHandleRowClassName = (record: any, index: any) => {
    if (record['state'] && record['state'] === 2) return 'ax-table-row-red';
    else return '-';
  };
}

export default AxStandardList;
